<template>
  <div class="ma-content-block lg:flex justify-between">
    <a-spin style="width: 100%;" :loading="spinLoading" tip="导出中">
      <template #tip>
        <div>
          <a-progress :animation="true" :stroke-width="10" track-color="#d3ccd6" width="130" size="large" type="circle"
            status='warning' :percent="percent" />
          <div style="margin-top: 10px;text-align: center;">{{ exportTxt }}</div>
        </div>

      </template>
    <sa-table ref="crudRef" :options="options" :columns="columns" :searchForm="searchForm" @resetSearch="resetSearch">
      <template #tableSearch>
        <a-col :span="6">
          <a-form-item field="id" label="发货ID">
            <a-input v-model="searchForm.id" placeholder="请输入" :allow-clear="true" @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="order" label="订单信息">
            <a-input v-model="searchForm.order" placeholder="订单ID|订单号" :allow-clear="true"
              @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="user" label="会员账号">
            <a-input v-model="searchForm.user" placeholder="会员账号" :allow-clear="true"
              @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="uid" label="会员UID">
            <a-input v-model="searchForm.uid" placeholder="会员UID" :allow-clear="true"
              @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="transaction_no" label="交易单号">
            <a-input v-model="searchForm.transaction_no" placeholder="请输入" :allow-clear="true"
              @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="address_user" label="联系人">
            <a-input v-model="searchForm.address_user" placeholder="请输入" :allow-clear="true"
              @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="sku" label="SKU">
            <a-input v-model="searchForm.sku" placeholder="请输入" :allow-clear="true" @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="express_code" label="物流单号">
            <a-input v-model="searchForm.express_code" placeholder="请输入" :allow-clear="true"
              @keydown.enter="refresh"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="state" label="发货状态">
            <sa-select v-model="searchForm.state" :data="paramsData.state" @change="refresh"></sa-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item field="send_type" label="发货类型">
            <sa-select v-model="searchForm.send_type" :data="paramsData.send_type" @change="refresh"></sa-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="shipping_time" label="发货日期">
            <a-range-picker v-model="searchForm.shipping_time" format="YYYY-MM-DD" :allow-clear="true"
            @change="refresh"></a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="create_time" label="创建日期">
            <a-range-picker v-model="searchForm.create_time" format="YYYY-MM-DD" :allow-clear="true"
            @change="refresh"></a-range-picker>
          </a-form-item>
        </a-col>
      </template>
      <template #id="{ record }">
        <div>发货ID:{{ record.id }}</div>
        <div>状态:{{ record.state_text }}</div>
        <div v-if="record.refund_state">退货状态:{{ record.refund_state_text }}</div>
        <div v-if="record.cloud_warn" style="color:red;width:180;text-wrap: wrap;">警告错误:{{ record.cloud_warn }}</div>
      </template>
      <template #order="{ record }">
        <div>订单ID:{{ record.order_id }}</div>
        <div>订单类型:{{ record.send_type_text }}</div>
        <div>订单SN:{{ record.order_sn }}</div>
      </template>
      <template #user="{ record }">
        <div>UID:{{ record.user_id }}</div>
        <div>会员名:{{ record.user?.user_name }}</div>
      </template>
      <template #area="{ record }">
        <div>地区:{{ record.area_name }}</div>
        <div>仓库:{{ record.stockroom_name }}</div>
      </template>
      <template #info="{ record }">
        <div v-if="record.orderInfo?.getMethods == 'post'">
          <div>国家:{{ record.address?.country }}</div>
          <div>洲/省:{{ record.address?.province }}</div>
          <div >城市:{{ record.address?.city }}</div>
          <a-tooltip :content="record.address?.address">
            <div >地址:{{ record.address?.address }}</div>
          </a-tooltip>
          
          <div>邮编:{{ record.address?.postcode }}</div>
          <div>电话:{{ record.address?.mobile }}</div>
          <div>邮箱:{{ record.address?.email }}</div>
          <div>联系人:{{ record.address?.name }}</div>
        </div>
        <div v-else>
          <div>自提人:{{ record.orderInfo?.ziti_info?.ziti_name }}</div>
          <div>自提电话:{{ record.orderInfo?.ziti_info?.ziti_mobile }}</div>
        </div>
      </template>
      <template #sku="{ record }">
        <div v-for="(itm, idx) in record.sku_list" :key="idx">
          <div>{{ itm.sku }}({{ itm.num }})</div>
        </div>
      </template>
      <template #goods="{ record }">
        <div v-for="(itm, idx) in record.sku_list" :key="idx">
          <div>{{ itm.sku_name }}({{ itm.num }})</div>
        </div>
      </template>
      <template #express="{ record }">
        <div>物流:{{ record.express_name }}</div>
        <div>单号:{{ record.express_code }}</div>
      </template>
      <template #time="{ record }">
        <div>生成时间:{{ record.create_time }}</div>
        <div>推送时间:{{ record.send_erp_time }}</div>
        <div>发货时间:{{ record.send_time }}</div>
      </template>
      <template #operationAfterExtend="{ record }">
        <div class="custom_btn">
            <div v-if="record.state==2 && record.getMethods == 'post'">
              <a-button class="yellow_color"  type="primary" size="mini" shape="round" @click="editSend(record)">修改发货</a-button>
            </div>
            <div v-else-if="record.stockroom_type == 2 && record.state == 1 && record.getMethods == 'post'">
              <a-popconfirm content="确定取消订单发货吗？" position="bottom" @ok="resend(record)">
                <a-button class="yellow_color"  type="primary" size="mini" shape="round" >重新推送</a-button>
              </a-popconfirm>
              
            </div>
            <div v-if="record.stockroom_type == 2 && (record.state>0 || record.send_erp_time) && record.getMethods=='post'">
              <a-button  type="primary" size="mini" shape="round" @click="push(record)">推送记录</a-button>
              <a-button  type="primary" size="mini" shape="round" @click="express_line(record)">物流轨迹</a-button>
            </div>
        </div>
        <!-- <div v-if="record.stockroom_type == 1">
          <div v-if="record.state == 0 && record.stockroom_id == 1">
            <div v-if="record.getMethods != 'post'">
              <a-button type="primary" size="mini" shape="round" class="yellow_color"   @click="send('tw_ziti', record)">发货</a-button>
            </div>
            <div v-if="record.getMethods == 'post' && record.is_lidao == 1 && !record.express_code">
              <a-button type="primary" size="mini" shape="round" class="yellow_color" @click="send('tw_lidao', record)">发货</a-button>
            </div>
          </div>
          <div v-if="record.stockroom_type == 1 && record.state == 0 && record.stockroom_id != 1">
            <a-button type="primary" size="mini" shape="round" class="yellow_color" @click="send('other', record)">发货</a-button>
          </div>
        </div> -->
        <!-- <div v-if="record.stockroom_type == 2 && record.state == 0">
          <a-popconfirm content="确定馬上发货吗？" position="bottom" @ok="pushErp(record)">
            <a-button type="primary" size="mini" shape="round" class="green_color">推送ERP</a-button>
          </a-popconfirm>
        </div> -->
        <!-- <a-button type="primary" size="mini" shape="round"  @click="handleDetail(record)">日志</a-button> -->
        <!-- <a-button type="primary" size="mini" shape="round"  @click="handleDetail(record)"></a-button> -->
        <!-- <a-dropdown :popup-max-height="false"
          v-if="(record.state == 2 && record.getMethods == 'post') || (record.stockroom_type == 2 && record.state == 1) || (record.stockroom_type == 2 && (record.state > 0 || record.send_erp_time) && record.getMethods == 'post')">
          <a-button type="primary" size="mini" shape="round" class="grew_color">更多<icon-down /></a-button>
          <template #content>
            <a-doption v-if="record.state == 2 && record.getMethods == 'post'" @click="editSend(record)">修改发货</a-doption>
            <a-doption v-if="record.stockroom_type == 2 && record.state == 1" @click="revoke(record)">撤销重新发货</a-doption>
            <a-doption
              v-if="record.stockroom_type == 2 && (record.state > 0 || record.send_erp_time) && record.getMethods == 'post'"
              @click="push(record)">推送记录</a-doption>
          </template>
        </a-dropdown> -->
      </template>
      <template #tableBeforeButtons>
        <a-button type="primary" size="medium" :loading="exportLoading" status="warning"
        style="padding:0 20px;" @click="handleExport"><icon-share-external />导出</a-button>
      </template>
    </sa-table>
    </a-spin>
    <sa-operation @cancel="del.visible = false" @ok="refresh" :visible="del.visible" :id="del.id"
      :api="del.api"></sa-operation>
    <!-- 编辑表单 -->
    <detail ref="detailRef" @success="refresh" />
    <send-form ref="sendRef" @success="refresh" />
    <update-express ref="updateExpressRef" @success="refresh" />
    <revoke-send ref="revokeRef" @success="refresh"></revoke-send>
    <push-record ref="pushRef" @success="refresh"></push-record>
    <expressLine ref="expressRef"></expressLine>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed, watch } from 'vue'
import AsApi from '@/api/system/afterSale'
import { Message } from '@arco-design/web-vue'
import SaTable from '@cps/sa-table/index.vue'
import SaSelect from '@cps/sa-select/index.vue'
import { throttle } from 'lodash';
import tool from '@/utils/tool'
import sendForm from './send.vue'
const expressRef=ref()
import detail from './detail.vue'
import expressLine from './expressLine.vue'
import updateExpress from './updateExpress.vue'
import revokeSend from './revokeSend.vue'
import pushRecord from './pushRecord.vue';
const crudRef = ref()
const exportLoading = ref(false)
const spinLoading = ref(false)
const detailRef = ref()
const sendRef = ref()
const revokeRef = ref()
const updateExpressRef = ref()
const pushRef = ref()
const del = ref({
  visible: false,
  id: '',
  api: '',
})
const searchForm = ref({
  order: '',
  user: '',
  state: 99,
  transaction_no: '',
  send_type: 99,
  address_user: "",
  sku: "",
  express_code: '',
  shipping_time: [],
  create_time: [],
  uid:'',
  id: '',
})
const options = reactive({
  api: AsApi.output_order_list,//表格数据接口
  operationColumnWidth: 200,//操作欄
  showSearch: true,
  columnAlign: 'left',
  pageSimple: false,//是否展示操作欄有 以及工具欄
  isTreeTable: false,
  showLine: false,
  add: {//頂部新增按鈕
    show: false,
    auth: ['/core/menu/save'],
    func: async () => {
      editRef.value?.open()
    },
  },
  edit: {//操作欄编辑按鈕
    show: false,
    auth: ['/core/menu/update'],
    func: async (record) => {
      editRef.value?.open('edit', record)
      editRef.value?.setFormData(record)
    },
  },
  isExpand: false,//展開所有子樹
})
const columns = reactive([
  { title: 'ID|状态', dataIndex: 'id', width: 180 },
  { title: '订单号', dataIndex: 'order', width: 250 },
  { title: '订单会员', dataIndex: 'user', width: 180 },
  { title: '地区｜仓库', dataIndex: 'area', width: 200 },
  { title: '收货信息', dataIndex: 'info', width: 230,ellipsis:true },
  { title: 'SKU', dataIndex: 'sku', width: 230 },
  { title: '商品', dataIndex: 'goods', width: 180 },
  { title: '物流单号', dataIndex: 'express', width: 180 },
  { title: '时间', dataIndex: 'time', width: 250 },
])

const initPage = async () => {

}
const resend = async (record) => { 
  const { data } = await AsApi.aftersale_output_cancel_send({ id: record.id })
  Message.success('操作成功')
   refresh()
}
const handleDetail = async (record) => {
  detailRef.value?.open(record)
}
const paramsData = ref({})
const getParams = async () => {
  const { data } = await AsApi.output_order_list_params()
  paramsData.value = { ...data }
  paramsData.value.state = tool.simpleTransformArray(data.state)
  paramsData.value.send_type = tool.simpleTransformArray(data.send_type)
  paramsData.value.state.unshift({ value: -1, title: '订单退货' })
  paramsData.value.state.unshift({ value: 99, title: '全部' })
  paramsData.value.send_type.unshift({ value: 99, title: '全部' })
  console.log('1', paramsData.value);
}
const refresh = async () => {
  crudRef.value?.refresh()
}
const resetSearch = () => {
  searchForm.value.send_erp_time = []
  searchForm.value.shipping_time = []
  searchForm.value.create_time = []
}

// 发货
const send = async (type, record) => {
  sendRef.value?.open(type, record)
}
const editSend = async (record) => {
  updateExpressRef.value?.open('updateExpress', record)
}
const pushErp = async (record) => {
  del.value.api = AsApi.erp_output_order
  del.value.id = record.id
  del.value.visible = true
}
const delGoods = async (id) => {
  del.value.api = AsApi.del_goods
  del.value.id = id
  del.value.visible = true
}
const revoke = async (record) => {
  revokeRef.value?.open('', record)
}
const push = async (record) => {
  pushRef.value?.open(record)
}
const express_line=(record) => {
  expressRef.value?.open(record)
}
const percent=ref(0)
const intervalId = ref(null)
const handleExport = async () => {
  percent.value = 0
  let params = { ...searchForm.value }
  const { data, code } = await AsApi.export_create_task_output(params)
  if (code == 200) {
    spinLoading.value = true
    const id = data.id;
    // 定义定时器
    intervalId.value = setInterval(async () => {
      try {
        const res = await AsApi.export_create_progress_output({ id });
        percent.value = Number(res.data?.percent) / 100
        console.log('进度', percent.value);
        // 判断进度是否达到预期状态，满足条件则停止定时器
        if (res.code === 200 && res.data.state == 1) {
          const url = `${import.meta.env.VITE_APP_BASE_URL}${res.data.excel_path}`
          window.location.href = url;
          spinLoading.value = false
          clearInterval(intervalId.value); // 清除定时器
        } else if (res.code === 0) {
          spinLoading.value = false
          clearInterval(intervalId.value);
        }
      } catch {
        spinLoading.value = false
        clearInterval(intervalId.value);
      }
    }, 2000); // 每2秒执行一次请求
  }
}
onMounted(async () => {
  initPage()
  refresh()
  getParams()
})
</script>

<style scoped>
.custom_btn{
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
}
.icon {
  width: 1em;
}

.over{
  word-break: break-word;
  overflow-wrap: break-word;
  white-space: normal;
}
</style>